<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Library Management System</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .hidden {
            display: none;
        }

        .feedback-window {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }

        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }

        .error {
            background-color: #f2dede;
            color: #a94442;
        }

        .warning {
            background-color: #fcf8e3;
            color: #8a6d3b;
        }
    </style>
</head>

<body>
    <nav>
        <ul>
            <li><a href="index.html">Home</a></li>
            <li><a href="course_management.html">Course Management</a></li>
            <li><a href="social_life.html">Social Life</a></li>
            <li><a href="data_display.html">Data Display</a></li>
        </ul>
    </nav>
    <div class="container">
        <h1>Library Management System</h1>

        <!-- User Login Section -->
        <div class="box" id="loginSection">
            <h2>Student Login</h2>
            <input type="text" id="studentId" placeholder="Enter your student ID">
            <button id="loginBtn">Login</button>
            <div class="feedback-window hidden" id="loginFeedback"></div>
        </div>

        <!-- Main Content (shown after login) -->
        <div id="mainContent" class="hidden">
            <div class="box">
                <h2>Welcome, <span id="studentName"></span></h2>
                <p>Borrowed Books: <span id="currentBorrowed">0</span>/7 | 
                   Credit Score: <span id="creditScore">3</span></p>
            </div>

            <div class="box">
                <h2>Add New Book</h2>
                <label for="bookTitle">Title:</label>
                <input type="text" id="bookTitle" placeholder="Enter book title">
                <label for="bookAuthor">Author:</label>
                <input type="text" id="bookAuthor" placeholder="Enter book author">
                <label for="bookYear">Year:</label>
                <input type="number" id="bookYear" placeholder="Enter publication year">
                <label for="bookCopies">Copies:</label>
                <input type="number" id="bookCopies" placeholder="Number of copies" value="1">
                <button id="addNewBook">Add Book</button>
                <div class="feedback-window hidden" id="addBookFeedback"></div>
            </div>

            <div class="box">
                <h2>Search Books</h2>
                <input type="text" id="searchInput" placeholder="Search by title, author, or year">
                <button id="searchBooks">Search</button>
                <table id="searchResults" class="hidden">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Author</th>
                            <th>Year</th>
                            <th>Available</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="searchResultsBody"></tbody>
                </table>
                <div class="feedback-window hidden" id="searchFeedback"></div>
            </div>

            <div class="box">
                <h2>My Borrowed Books</h2>
                <button id="showBorrowed">Show My Books</button>
                <table id="borrowedBooks" class="hidden">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Borrow Date</th>
                            <th>Due Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="borrowedBooksBody"></tbody>
                </table>
                <div class="feedback-window hidden" id="borrowedFeedback"></div>
            </div>

            <div class="box">
                <h2>Reserve a Book</h2>
                <input type="text" id="reserveBookTitle" placeholder="Enter book title to reserve">
                <button id="reserveBook">Reserve</button>
                <div class="feedback-window hidden" id="reserveFeedback"></div>
            </div>

            <div class="box">
                <h2>Report Lost Book</h2>
                <input type="text" id="lostBookTitle" placeholder="Enter title of lost book">
                <button id="reportLost">Report</button>
                <div class="feedback-window hidden" id="lostBookFeedback"></div>
            </div>

            <div class="box">
                <h2>Book Usage Statistics</h2>
                <button id="showStats">Show Statistics</button>
                <table id="statsTable" class="hidden">
                    <thead>
                        <tr>
                            <th>Rank</th>
                            <th>Title</th>
                            <th>Total Borrows</th>
                            <th>Current Borrows</th>
                            <th>Waitlist</th>
                        </tr>
                    </thead>
                    <tbody id="statsBody"></tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // Library data structure
        const library = {
            books: [],
            students: {},
            waitlists: {},
            transactions: [],
            bookStats: {}
        };

        // Current logged in student
        let currentStudent = null;

        // Initialize with data from books.json
        function initializeLibrary() {
            fetch('books.json')
                .then(response => response.json())
                .then(data => {
                    library.books = data.books.map(book => {
                        return {
                            ...book,
                            available: book.number_of_copies,
                            borrowedBy: [],
                            waitingList: []
                        };
                    });

                    // Initialize book statistics
                    library.books.forEach(book => {
                        library.bookStats[book.title] = {
                            totalBorrows: 0,
                            currentBorrows: 0,
                            waitlist: 0
                        };
                    });

                    console.log('Library initialized with books:', library.books);
                })
                .catch(error => {
                    console.error('Error loading books:', error);
                });
        }

        // Show feedback message
        function showFeedback(element, message, type) {
            element.textContent = message;
            element.className = `feedback-window ${type}`;
            element.classList.remove('hidden');
            
            setTimeout(() => {
                element.classList.add('hidden');
            }, 5000);
        }

        // Login function
        document.getElementById('loginBtn').addEventListener('click', function() {
            const studentId = document.getElementById('studentId').value.trim();
            const feedback = document.getElementById('loginFeedback');
            
            if (!studentId) {
                showFeedback(feedback, 'Please enter your student ID', 'error');
                return;
            }

            // If student doesn't exist, create new account
            if (!library.students[studentId]) {
                library.students[studentId] = {
                    name: "Student " + studentId,
                    borrowedBooks: [],
                    credits: 3
                };
            }

            currentStudent = studentId;
            document.getElementById('studentName').textContent = library.students[studentId].name;
            document.getElementById('currentBorrowed').textContent = library.students[studentId].borrowedBooks.length;
            document.getElementById('creditScore').textContent = library.students[studentId].credits;
            
            document.getElementById('loginSection').classList.add('hidden');
            document.getElementById('mainContent').classList.remove('hidden');
            showFeedback(feedback, 'Login successful!', 'success');
        });

        // Add new book
        document.getElementById('addNewBook').addEventListener('click', function() {
            const title = document.getElementById('bookTitle').value.trim();
            const author = document.getElementById('bookAuthor').value.trim();
            const year = document.getElementById('bookYear').value.trim();
            const copies = parseInt(document.getElementById('bookCopies').value) || 1;
            const feedback = document.getElementById('addBookFeedback');
            
            if (!title || !author || !year) {
                showFeedback(feedback, 'Please fill all fields', 'error');
                return;
            }

            const newBook = {
                id: library.books.length + 1,
                title,
                authors: [author],
                year: parseInt(year),
                number_of_copies: copies,
                available: copies,
                borrowedBy: [],
                waitingList: []
            };

            library.books.push(newBook);
            library.bookStats[title] = {
                totalBorrows: 0,
                currentBorrows: 0,
                waitlist: 0
            };
            
            // Clear form
            document.getElementById('bookTitle').value = '';
            document.getElementById('bookAuthor').value = '';
            document.getElementById('bookYear').value = '';
            document.getElementById('bookCopies').value = '1';
            
            showFeedback(feedback, `Book "${title}" added successfully with ${copies} copies`, 'success');
        });

        // Search books
        document.getElementById('searchBooks').addEventListener('click', function() {
            const query = document.getElementById('searchInput').value.toLowerCase();
            const feedback = document.getElementById('searchFeedback');
            const resultsBody = document.getElementById('searchResultsBody');
            
            if (!query) {
                showFeedback(feedback, 'Please enter a search term', 'error');
                return;
            }

            resultsBody.innerHTML = '';
            const results = library.books.filter(book => 
                book.title.toLowerCase().includes(query) || 
                book.authors.some(author => author.toLowerCase().includes(query)) ||
                book.year.toString().includes(query)
            );

            if (results.length === 0) {
                showFeedback(feedback, 'No books found matching your search', 'warning');
                document.getElementById('searchResults').classList.add('hidden');
                return;
            }

            document.getElementById('searchResults').classList.remove('hidden');

            results.forEach(book => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${book.title}</td>
                    <td>${book.authors.join(', ')}</td>
                    <td>${book.year}</td>
                    <td>${book.available}/${book.number_of_copies}</td>
                    <td>
                        <button onclick="borrowBook('${book.title.replace(/'/g, "\\'")}')" ${book.available === 0 ? 'disabled' : ''}>
                            ${book.available === 0 ? 'Not Available' : 'Borrow'}
                        </button>
                        <button onclick="joinWaitlist('${book.title.replace(/'/g, "\\'")}')" ${book.available > 0 ? 'disabled' : ''}>
                            Join Waitlist
                        </button>
                    </td>
                `;
                resultsBody.appendChild(row);
            });

            showFeedback(feedback, `Found ${results.length} books`, 'success');
        });

        // Show borrowed books
        document.getElementById('showBorrowed').addEventListener('click', function() {
            const table = document.getElementById('borrowedBooks');
            const body = document.getElementById('borrowedBooksBody');
            const feedback = document.getElementById('borrowedFeedback');
            
            if (!currentStudent) {
                showFeedback(feedback, 'Please login first', 'error');
                return;
            }

            body.innerHTML = '';
            const student = library.students[currentStudent];
            
            if (student.borrowedBooks.length === 0) {
                body.innerHTML = '<tr><td colspan="4">You have no borrowed books</td></tr>';
            } else {
                student.borrowedBooks.forEach(bookTitle => {
                    const book = library.books.find(b => b.title === bookTitle);
                    if (book) {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${book.title}</td>
                            <td>${new Date().toLocaleDateString()}</td>
                            <td>${new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toLocaleDateString()}</td>
                            <td><button onclick="returnBook('${book.title.replace(/'/g, "\\'")}')">Return</button></td>
                        `;
                        body.appendChild(row);
                    }
                });
            }
            
            table.classList.toggle('hidden');
        });

        // Reserve book
        document.getElementById('reserveBook').addEventListener('click', function() {
            const title = document.getElementById('reserveBookTitle').value.trim();
            const feedback = document.getElementById('reserveFeedback');
            
            if (!title) {
                showFeedback(feedback, 'Please enter a book title', 'error');
                return;
            }

            const book = library.books.find(b => b.title.toLowerCase() === title.toLowerCase());
            
            if (!book) {
                showFeedback(feedback, 'Book not found in library', 'error');
                return;
            }

            if (book.available > 0) {
                showFeedback(feedback, 'Book is available for borrowing, no need to reserve', 'warning');
                return;
            }

            if (book.waitingList.includes(currentStudent)) {
                showFeedback(feedback, 'You are already on the waitlist for this book', 'warning');
                return;
            }

            book.waitingList.push(currentStudent);
            library.bookStats[book.title].waitlist = book.waitingList.length;
            showFeedback(feedback, 
                `Added to waitlist for "${book.title}". Position: ${book.waitingList.length}`, 
                'success');
        });

        // Report lost book
        document.getElementById('reportLost').addEventListener('click', function() {
            const title = document.getElementById('lostBookTitle').value.trim();
            const feedback = document.getElementById('lostBookFeedback');
            
            if (!title) {
                showFeedback(feedback, 'Please enter a book title', 'error');
                return;
            }

            const student = library.students[currentStudent];
            const bookIndex = student.borrowedBooks.findIndex(bookTitle => 
                bookTitle.toLowerCase() === title.toLowerCase()
            );

            if (bookIndex === -1) {
                showFeedback(feedback, 'You have not borrowed this book', 'error');
                return;
            }

            // Remove from borrowed list
            const bookTitle = student.borrowedBooks[bookIndex];
            student.borrowedBooks.splice(bookIndex, 1);
            
            // Decrease credit
            student.credits -= 1;
            document.getElementById('creditScore').textContent = student.credits;
            document.getElementById('currentBorrowed').textContent = student.borrowedBooks.length;
            
            // Update book availability
            const book = library.books.find(b => b.title === bookTitle);
            if (book) {
                book.borrowedBy = book.borrowedBy.filter(id => id !== currentStudent);
                book.available += 1;
                library.bookStats[book.title].currentBorrows = book.borrowedBy.length;
                
                // Notify next in waitlist if any
                if (book.waitingList.length > 0) {
                    const nextStudentId = book.waitingList.shift();
                    library.bookStats[book.title].waitlist = book.waitingList.length;
                    showFeedback(feedback, 
                        `Book reported lost. Credit decreased. Next student on waitlist has been notified.`, 
                        'warning');
                } else {
                    showFeedback(feedback, 
                        `Book "${title}" reported lost. Your credit score has decreased by 1.`, 
                        'warning');
                }
            }
        });

        // Show statistics
        document.getElementById('showStats').addEventListener('click', function() {
            const table = document.getElementById('statsTable');
            const body = document.getElementById('statsBody');
            
            body.innerHTML = '';
            
            // Sort books by popularity
            const sortedStats = Object.entries(library.bookStats)
                .sort((a, b) => {
                    const aScore = a[1].totalBorrows + a[1].waitlist;
                    const bScore = b[1].totalBorrows + b[1].waitlist;
                    return bScore - aScore;
                });

            sortedStats.forEach(([title, stats], index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${title}</td>
                    <td>${stats.totalBorrows}</td>
                    <td>${stats.currentBorrows}</td>
                    <td>${stats.waitlist}</td>
                `;
                body.appendChild(row);
            });
            
            table.classList.toggle('hidden');
        });

        // Borrow book function
        window.borrowBook = function(title) {
            if (!currentStudent) {
                showFeedback(document.getElementById('searchFeedback'), 'Please login first', 'error');
                return;
            }

            const book = library.books.find(b => b.title === title);
            const student = library.students[currentStudent];
            const feedback = document.getElementById('searchFeedback');
            
            if (!book || !student) {
                showFeedback(feedback, 'Error processing request', 'error');
                return;
            }

            if (book.available <= 0) {
                showFeedback(feedback, 'No copies available', 'error');
                return;
            }

            if (student.borrowedBooks.length >= 7) {
                showFeedback(feedback, 'You have reached your borrowing limit (7 books)', 'error');
                return;
            }

            if (student.borrowedBooks.includes(title)) {
                showFeedback(feedback, 'You have already borrowed this book', 'error');
                return;
            }

            book.available -= 1;
            book.borrowedBy.push(currentStudent);
            student.borrowedBooks.push(title);
            
            // Update stats
            library.bookStats[title].totalBorrows += 1;
            library.bookStats[title].currentBorrows = book.borrowedBy.length;
            
            document.getElementById('currentBorrowed').textContent = student.borrowedBooks.length;
            showFeedback(feedback, `Successfully borrowed "${title}"`, 'success');
            
            // Refresh search results
            document.getElementById('searchBooks').click();
        };

        // Return book function
        window.returnBook = function(title) {
            if (!currentStudent) {
                showFeedback(document.getElementById('borrowedFeedback'), 'Please login first', 'error');
                return;
            }

            const book = library.books.find(b => b.title === title);
            const student = library.students[currentStudent];
            const feedback = document.getElementById('borrowedFeedback');
            
            if (!book || !student) {
                showFeedback(feedback, 'Error processing request', 'error');
                return;
            }

            const bookIndex = student.borrowedBooks.indexOf(title);
            if (bookIndex === -1) {
                showFeedback(feedback, 'You have not borrowed this book', 'error');
                return;
            }

            book.available += 1;
            book.borrowedBy = book.borrowedBy.filter(id => id !== currentStudent);
            student.borrowedBooks.splice(bookIndex, 1);
            
            // Update stats
            library.bookStats[title].currentBorrows = book.borrowedBy.length;
            
            document.getElementById('currentBorrowed').textContent = student.borrowedBooks.length;
            showFeedback(feedback, `Successfully returned "${title}"`, 'success');
            
            // Notify next in waitlist if any
            if (book.waitingList.length > 0) {
                const nextStudentId = book.waitingList.shift();
                library.bookStats[title].waitlist = book.waitingList.length;
                showFeedback(feedback, 
                    `Book returned. Next student on waitlist has been notified.`, 
                    'warning');
            }
            
            // Refresh borrowed books list
            document.getElementById('showBorrowed').click();
        };

        // Join waitlist function
        window.joinWaitlist = function(title) {
            if (!currentStudent) {
                showFeedback(document.getElementById('searchFeedback'), 'Please login first', 'error');
                return;
            }

            const book = library.books.find(b => b.title === title);
            const feedback = document.getElementById('searchFeedback');
            
            if (!book) {
                showFeedback(feedback, 'Book not found', 'error');
                return;
            }

            if (book.available > 0) {
                showFeedback(feedback, 'Book is available for borrowing', 'warning');
                return;
            }

            if (book.waitingList.includes(currentStudent)) {
                showFeedback(feedback, 'You are already on the waitlist for this book', 'warning');
                return;
            }

            book.waitingList.push(currentStudent);
            library.bookStats[title].waitlist = book.waitingList.length;
            showFeedback(feedback, 
                `Added to waitlist for "${title}". Position: ${book.waitingList.length}`, 
                'success');
        };

        // Initialize the library when page loads
        window.onload = initializeLibrary;
    </script>
</body>

</html>